// 引入API模块和缓存模块
import { departmentAPI, doctorAPI, roleAPI } from './api'
import { localCache } from './cache'

// 全局缓存键
const CACHE_KEYS = {
  DEPARTMENTS: 'form_departments',
  DOCTORS: 'form_doctors',
  ROLES: 'form_roles'
}

// 获取部门选项
export const getDepartmentOptions = async (forceRefresh = false) => {
  // 如果不强制刷新且缓存中有数据，则使用缓存
  if (!forceRefresh) {
    const cachedData = localCache.get(CACHE_KEYS.DEPARTMENTS)
    if (cachedData) {
      return cachedData
    }
  }

  try {
    const response = await departmentAPI.getAllDepartments()
    
    if (response.success && response.data) {
      // 转换部门数据为选项格式
      const options = Array.isArray(response.data) 
        ? response.data.map((dept, index) => {
            // 确保每个科室都有一个有效的value属性
            const value = dept.id || dept._id || dept.departmentId || String(index + 1);
            return {
              value: value,
              label: dept.name || `科室${index + 1}`,
              ...dept
            };
          })
        : [];
      
      // 缓存数据
      localCache.set(CACHE_KEYS.DEPARTMENTS, options)
      return options
    }
    
    // 如果后端没有返回有效数据，提供默认选项
    const defaultOptions = [
      { value: '1', label: '内科' },
      { value: '2', label: '外科' },
      { value: '3', label: '儿科' },
      { value: '4', label: '妇产科' },
      { value: '5', label: '眼科' },
      { value: '6', label: '口腔科' }
    ];
    
    // 缓存默认数据
    localCache.set(CACHE_KEYS.DEPARTMENTS, defaultOptions);
    return defaultOptions;
  } catch (error) {
    console.error('获取部门选项失败:', error)
    
    // 返回默认科室选项而不是空数组
    const defaultOptions = [
      { value: '1', label: '内科' },
      { value: '2', label: '外科' },
      { value: '3', label: '儿科' },
      { value: '4', label: '妇产科' },
      { value: '5', label: '眼科' },
      { value: '6', label: '口腔科' }
    ];
    
    // 缓存默认数据
    localCache.set(CACHE_KEYS.DEPARTMENTS, defaultOptions);
    return defaultOptions;
  }
}

// 获取医生选项
export const getDoctorOptions = async (forceRefresh = false) => {
  // 如果不强制刷新且缓存中有数据，则使用缓存
  if (!forceRefresh) {
    const cachedData = localCache.get(CACHE_KEYS.DOCTORS)
    if (cachedData) {
      return cachedData
    }
  }

  try {
    const response = await doctorAPI.getDoctors()
    console.log('医生API响应:', response)
    
    let doctorsData = []
    
    // 标准格式：{success: true, data: {doctors: [...], total: n}}
    if (response.success && response.data && response.data.doctors) {
      doctorsData = response.data.doctors
    }
    // 数组在data中：{success: true, data: [...]}
    else if (response.success && response.data && Array.isArray(response.data)) {
      doctorsData = response.data
    }
    // 响应本身是数组
    else if (Array.isArray(response)) {
      doctorsData = response
    }
    // 直接包含doctors字段的对象
    else if (response.doctors && Array.isArray(response.doctors)) {
      doctorsData = response.doctors
    }
    // 其他情况
    else {
      console.warn('未识别的医生API响应格式:', response)
      doctorsData = []
    }
    
    // 转换为选项格式
    const options = doctorsData.map(doctor => ({
      value: doctor.id || doctor._id,
      label: doctor.name,
      ...doctor
    }))
    
    // 缓存数据
    localCache.set(CACHE_KEYS.DOCTORS, options)
    return options
  } catch (error) {
    console.error('获取医生选项失败:', error)
    // 发生错误时，返回空数组而不是抛出异常
    return []
  }
}

// 获取部门下的医生
export const getDepartmentDoctors = async (departmentId) => {
  if (!departmentId) return []
  
  try {
    const response = await doctorAPI.getDoctorsByDepartment(departmentId)
    
    if (response.success && response.data) {
      // 转换医生数据为选项格式
      return Array.isArray(response.data) 
        ? response.data.map(doctor => ({
            value: doctor.id || doctor._id,
            label: doctor.name,
            ...doctor
          }))
        : []
    }
    return []
  } catch (error) {
    console.error(`获取部门(${departmentId})下的医生失败:`, error)
    return []
  }
}

// 获取角色选项
export const getRoleOptions = async (forceRefresh = false) => {
  // 如果不强制刷新且缓存中有数据，则使用缓存
  if (!forceRefresh) {
    const cachedData = localCache.get(CACHE_KEYS.ROLES)
    if (cachedData) {
      return cachedData
    }
  }

  try {
    const response = await roleAPI.getRoles()
    console.log('角色API响应:', response)
    
    // 如果服务器返回权限不足错误，使用默认角色
    if (response.success === false && response.message === '权限不足') {
      console.log('没有权限获取角色，使用默认角色数据')
      
      // 根据用户角色提供最小必要的角色数据
      const userStore = window.userStore || {}
      const userRole = userStore.userRole || localStorage.getItem('userRole') || ''
      
      // 针对不同角色提供不同的默认数据
      let defaultRoles = []
      
      if (userRole === 'patient') {
        defaultRoles = [
          { value: 'patient', label: '患者' }
        ]
      } else if (userRole === 'doctor') {
        defaultRoles = [
          { value: 'doctor', label: '医生' },
          { value: 'patient', label: '患者' }
        ]
      } else {
        defaultRoles = [
          { value: 'admin', label: '管理员' },
          { value: 'doctor', label: '医生' },
          { value: 'nurse', label: '护士' },
          { value: 'patient', label: '患者' }
        ]
      }
      
      // 缓存默认角色数据
      localCache.set(CACHE_KEYS.ROLES, defaultRoles)
      return defaultRoles
    }
    
    let rolesData = []
    
    // 标准格式：{success: true, data: {roles: [...], total: n}}
    if (response.success && response.data && response.data.roles) {
      rolesData = response.data.roles
    }
    // 数组在data中：{success: true, data: [...]}
    else if (response.success && response.data && Array.isArray(response.data)) {
      rolesData = response.data
    }
    // 响应本身是数组
    else if (Array.isArray(response)) {
      rolesData = response
    }
    // 直接包含roles字段的对象
    else if (response.roles && Array.isArray(response.roles)) {
      rolesData = response.roles
    }
    // 其他情况
    else {
      console.warn('未识别的角色API响应格式:', response)
      rolesData = []
    }
    
    // 转换为选项格式
    const options = rolesData.map(role => ({
      value: role.id || role._id || role.name,
      label: role.displayName || role.name,
      ...role
    }))
    
    // 缓存数据
    localCache.set(CACHE_KEYS.ROLES, options)
    return options
  } catch (error) {
    console.error('获取角色选项失败:', error)
    
    // 出错时返回默认角色数据而不是空数组
    const defaultRoles = [
      { value: 'admin', label: '管理员' },
      { value: 'doctor', label: '医生' },
      { value: 'nurse', label: '护士' },
      { value: 'patient', label: '患者' }
    ]
    
    // 缓存默认角色数据
    localCache.set(CACHE_KEYS.ROLES, defaultRoles)
    return defaultRoles
  }
}

// 刷新所有表单数据
export const refreshAllData = async () => {
  try {
    const userStore = window.userStore || {}
    const userRole = userStore.userRole || localStorage.getItem('userRole') || ''
    console.log('当前用户角色:', userRole)
    
    // 默认需要加载的数据
    const dataPromises = [getDepartmentOptions(true)]
    
    // 患者角色不需要角色数据，使用模拟数据即可
    if (userRole === 'patient') {
      console.log('患者用户使用本地数据')
      
      // 对于患者，只尝试加载医生数据，不加载角色数据
      dataPromises.push(getDoctorOptions(true))
      
      // 使用默认角色数据
      const roles = [
        { value: 'patient', label: '患者' }
      ]
      
      const [departments, doctors] = await Promise.all(dataPromises)
      
      return {
        departments,
        doctors,
        roles
      }
    } else {
      // 非患者用户加载所有数据
      dataPromises.push(getDoctorOptions(true))
      dataPromises.push(getRoleOptions(true))
      
      const [departments, doctors, roles] = await Promise.all(dataPromises)
      
      return {
        departments,
        doctors,
        roles
      }
    }
  } catch (error) {
    console.error('刷新表单数据失败:', error)
    // 返回对象而不是抛出异常，避免中断程序
    return {
      departments: [],
      doctors: [],
      roles: []
    }
  }
} 